package com.fruit.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.fruit.constants.AfterSalesServiceConstant;
import com.fruit.constants.OrderConstant;
import com.fruit.mapper.order.DshOrderMapper;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.mapper.refund.AfterSalesServiceMapper;
import com.fruit.mapper.user.UserMapper;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderGoods;
import com.fruit.pojo.refund.AfterSalesService;
import com.fruit.pojo.refund.AfterSalesServiceGoods;
import com.fruit.pojo.refund.AfterSalesServiceRefund;
import com.fruit.pojo.refund.Question;
import com.fruit.pojo.refund.RefundCodex;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.order.OrderRefundManager;
import com.fruit.service.pic.PictureManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DataUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

/** 订单退款类
 * 修改时间：2016.07.15
 */
@Service("orderRefundService")
public class OrderRefundService implements OrderRefundManager{

	@Autowired
	private DshOrderMapper dshOrderMapper;
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private AfterSalesServiceMapper afterSalesServiceMapper;
	
	@Autowired
	private PictureManager pictureService;
	
	@Override
	public Map<String, Object> getRefundApply(Order o) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String code = o.getOrderCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		Order order = dshOrderMapper.getOrder(id);
		if(order == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_not_exists", "订单不存在!"));
			return resMap;
		}
		
		if(!(OrderConstant.WAIT_SEND.equals(order.getState())||OrderConstant.ALREADY_SEND.equals(order.getState())
				||OrderConstant.STATE_REFUND.equals(order.getState()))){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_error", "该订单不能申请退款!"));
			return resMap;
		}
		
		//判断订单退款状态
		if(!OrderConstant.IS_REFUND_NO.equals(order.getIsRefund())){
			AfterSalesService as = afterSalesServiceMapper.getSalesServiceById(order.getRefundId());
			as.setCode(as.getCodePre()+as.getId()+as.getCodeSuf());
			resMap.put("as", as);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "detail", "跳转退款详情!"));
			return resMap;
		}
		
		order.setOrderCode(order.getCodePre()+order.getId()+order.getCodeSuf());
		List<OrderGoods> ogList = orderMapper.getOrderGoodsList(order);
		RefundCodex rc = new RefundCodex();
		rc.setGoodsType(order.getIsAdvanceState());
		rc.setState(order.getState());
		rc = afterSalesServiceMapper.getRefundCodexByState(rc);
		
		if(rc == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统繁忙!"));
			return resMap;
		}
		
		for(OrderGoods og:ogList){
			og.setGoodsOffPrice(og.getTradePrice().multiply(new BigDecimal(og.getNumber())).multiply(rc.getRefundRatio()).divide(new BigDecimal(100), 2));
			og.setReturnPrice(og.getTradePrice().multiply(new BigDecimal(og.getNumber())).subtract(og.getGoodsOffPrice()));
		}
		
		resMap.put("order", order);
		resMap.put("ogList", ogList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public Map<String, Object> saveRefund(AfterSalesService as,MultipartFile[] imgs) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		AfterSalesServiceRefund asr = as.getAsr();
		Question asq = as.getAsq();
		
		if(StringUtils.isEmpty(as.getOrderCode())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_not_exists", "订单不存在!"));
			return resMap;
		}
		long orderId= Long.parseLong(as.getOrderCode().substring(4, as.getOrderCode().length() - 7));
		as.setOrderId(orderId);
		if(as.getGoodsIds() == null || as.getGoodsIds().length == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "not_select_goods", "请选择商品!"));
			return resMap;
		}
		
		BigDecimal returnPrice = DataUtil.getBigDecimal(asr.getReturnPrice());
		if(returnPrice.compareTo(BigDecimal.ZERO) <= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		
		if(StringUtils.isEmpty(asq.getContent())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "question_empty", "请输入问题描述!"));
			return resMap;
		}
		//判断订单是否存在
		Order order = dshOrderMapper.getOrder(as.getOrderId());
		if(order == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_not_exists", "订单不存在!"));
			return resMap;
		}
		//判断订单是否能退款
		if(!(OrderConstant.WAIT_SEND.equals(order.getState())||OrderConstant.ALREADY_SEND.equals(order.getState()))){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_error", "该订单不能申请退款!"));
			return resMap;
		}
		//判断订单退款状态
		if(!OrderConstant.IS_REFUND_NO.equals(order.getIsRefund())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_error", "该订单不能申请退款!"));
			return resMap;
		}
		
		
		//查询订单商品
		order.setGoodsIds(as.getGoodsIds());
		List<OrderGoods> ogList = orderMapper.getOrderGoodsList(order);
		if(ogList == null || ogList.size() != as.getGoodsIds().length){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "not_select_goods", "请选择商品!"));
			return resMap;
		}
		
		//查询规则
		RefundCodex rc = new RefundCodex();
		rc.setGoodsType(order.getIsAdvanceState());
		rc.setState(order.getState());
		rc = afterSalesServiceMapper.getRefundCodexByState(rc);
		
		if(rc == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统繁忙!"));
			return resMap;
		}
		BigDecimal realReturnPrice = new BigDecimal(0);
		BigDecimal realGoodsOffPrice = new BigDecimal(0);
		BigDecimal realTotalPrice = new BigDecimal(0);
		for(OrderGoods og:ogList){
			realGoodsOffPrice = realGoodsOffPrice.add(og.getTradePrice().multiply(new BigDecimal(og.getNumber())).multiply(rc.getRefundRatio()).divide(new BigDecimal(100), 2));		
			realTotalPrice = realTotalPrice.add(og.getTradePrice().multiply(new BigDecimal(og.getNumber())));
		}
		realReturnPrice = realTotalPrice.subtract(realGoodsOffPrice);
		//判断金额
		if(realReturnPrice.compareTo(asr.getReturnPrice()) != 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		
		if(OrderConstant.WAIT_SEND.equals(order.getState())){
			order.setIsRefund(OrderConstant.IS_REFUND_HANDEL);
		}else{
			order.setIsRefund(OrderConstant.IS_REFUND_GOODS_HANDEL);
		}
		
		 //插入售后申请记录
		 as.setCodePre(DateUtil.getYear());
		 as.setCodeSuf(CustomUtil.codeSuf(3, order.getUserId()));
		 as.setOrderCode(order.getCodePre()+order.getId()+order.getCodeSuf());
		 as.setOrderId(order.getId());
		 as.setUserId(order.getUserId());
		 as.setIsAuto(AfterSalesServiceConstant.NO_AUTO);
		 if(OrderConstant.WAIT_SEND.equals(order.getState())){
			 as.setType(AfterSalesServiceConstant.TYPE_REFUND);
		 }else{
			 as.setType(AfterSalesServiceConstant.TYPE_RETURN_GOODS);
		 }
		 
		 as.setState(AfterSalesServiceConstant.STATE_REVIEW);
		 as.setCreateTime(DateUtil.getTime());
		 afterSalesServiceMapper.saveSalesService(as);
		
		order.setRefundId(as.getId());
		//修改订单状态
		int num = afterSalesServiceMapper.updateOrderRefundState(order);
		
		if(num == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		}
		
		//上传图片
		StringBuffer pic = new StringBuffer();
		if(imgs != null && imgs.length >0){
			for(int i = 0;i<imgs.length;i++){
				MultipartFile img = imgs[i];
				Map<String, Object> imgResMap = pictureService.uploadPicture(img.getInputStream(), "view", 800, 800, 0.8f);
				int error = (Integer)imgResMap.get("error");
				if(error == 0){
					pic.append(imgResMap.get("url"));
					if(i != imgs.length - 1){
						pic.append(",");
					}
				}
			}		
		}
		//插入问题
		asq.setPic(pic.toString());	
		asq.setAfterSalesServiceId(as.getId());
		asq.setIsUser(AfterSalesServiceConstant.IS_USER);
		asq.setUserId(String.valueOf(order.getUserId()));
		asq.setCreateTime(DateUtil.getTime());
		afterSalesServiceMapper.saveSalesServiceQuestion(asq);
		//插入商品记录
		for(OrderGoods og : ogList){
			AfterSalesServiceGoods asg = new AfterSalesServiceGoods();
			asg.setAfterSalesServiceId(as.getId());
			asg.setGoodsId(og.getGoodsId());
			asg.setNum(og.getNumber());
			asg.setPrice(og.getTradePrice());
			asg.setRefundState(AfterSalesServiceConstant.TYPE_REFUND);
			afterSalesServiceMapper.saveSalesServiceGoods(asg);
		}
		//插入退款金额
		asr.setGoodsOffPrice(realGoodsOffPrice);
		asr.setTotalPrice(realTotalPrice);
		asr.setOtherOffPrice(new BigDecimal(0));
		asr.setSalesServiceId(as.getId());
		afterSalesServiceMapper.saveSalesServiceRefund(asr);
		
		resMap.put("code", as.getCodePre()+as.getId()+as.getCodeSuf());
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		return resMap;
		
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public Map<String, Object> getRefundDetail(AfterSalesService as) {
	
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String code = as.getCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		String codePre=code.substring(0,4);
		String codeSuf=code.substring(code.length()-7); 
		
		as.setId(id);
		as.setCodePre(codePre);
		as.setCodeSuf(codeSuf);
		
		AfterSalesService asn = afterSalesServiceMapper.getSalesServiceByCode(as);
		if(asn == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "service_not_exists", "服务单不存在!"));
			return resMap;
		}
		
		asn.setCode(code);
		AfterSalesServiceRefund asr = null;
		
		List<AfterSalesServiceGoods> asgList = null;
		if(AfterSalesServiceConstant.TYPE_REFUND.equals(asn.getType())||AfterSalesServiceConstant.TYPE_RETURN_GOODS.equals(asn.getType())){
			asr = afterSalesServiceMapper.getAfterSalesServiceRefund(as.getId());
			asgList = afterSalesServiceMapper.getAfterSalesServiceGoods(asn.getId());
			
			resMap.put("asn", asn);
			resMap.put("asr", asr);
			resMap.put("asgList", asgList);
			resMap.put("asgCnt", asgList.size());
		}
		UserInfo user = userMapper.getUserById(asn.getUserId());
		
		resMap.put("user", user);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public Map<String, Object> getQuestion(Question q) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			String code = q.getCode();
			long id= Long.parseLong(code.substring(4, code.length() - 7));
			q.setAfterSalesServiceId(id);
		List<Question> qList = afterSalesServiceMapper.getAfterSalesServiceQuestion(q);
		resMap.put("qList", qList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return resMap;
	}

	@Override
	public Map<String, Object> getQuestionPage(AfterSalesService as) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String code = as.getCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		String codePre=code.substring(0,4);
		String codeSuf=code.substring(code.length()-7); 
		
		as.setId(id);
		as.setCodePre(codePre);
		as.setCodeSuf(codeSuf);
		
		AfterSalesService asn = afterSalesServiceMapper.getSalesServiceByCode(as);
		if(asn == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "service_not_exists", "服务单不存在!"));
			return resMap;
		}
		if(!AfterSalesServiceConstant.STATE_REVIEW.equals(asn.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "service_error", "服务单异常!"));
			return resMap;
		}
		asn.setCode(code);
		resMap.put("asn", asn);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public Map<String, Object> saveQuestion(AfterSalesService as, MultipartFile[] imgs) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String code = as.getCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		String codePre=code.substring(0,4);
		String codeSuf=code.substring(code.length()-7); 
		
		as.setId(id);
		as.setCodePre(codePre);
		as.setCodeSuf(codeSuf);
		
		AfterSalesService asn = afterSalesServiceMapper.getSalesServiceByCode(as);
		if(asn == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "service_not_exists", "服务单不存在!"));
			return resMap;
		}
		if(!AfterSalesServiceConstant.STATE_REVIEW.equals(asn.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "service_error", "服务单异常!"));
			return resMap;
		}
		Question asq = as.getAsq();
		//上传图片
		StringBuffer pic = new StringBuffer();
		if(imgs != null && imgs.length >0){
			for(int i = 0;i<imgs.length;i++){
				MultipartFile img = imgs[i];
				Map<String, Object> imgResMap = pictureService.uploadPicture(img.getInputStream(), "view", 800, 800, 0.8f);
				int error = (Integer)imgResMap.get("error");
				if(error == 0){
					pic.append(imgResMap.get("url"));
					if(i != imgs.length - 1){
						pic.append(",");
					}
				}
			}		
		}
		//插入问题
		asq.setPic(pic.toString());	
		asq.setAfterSalesServiceId(asn.getId());
		asq.setIsUser(AfterSalesServiceConstant.IS_USER);
		asq.setUserId(String.valueOf(asn.getUserId()));
		asq.setCreateTime(DateUtil.getTime());
		afterSalesServiceMapper.saveSalesServiceQuestion(asq);
		
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
			
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		
	}
	
	
	
	
	
}
